package com.iphanta.community.common;

import com.iphanta.community.common.entity.DataResult;
import com.iphanta.community.common.utils.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * @author 墨声 E-mail: zehong.hongframe.huang@gmail.com
 * create time: 2/15/22 2:59 PM
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public DataResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request, HttpServletResponse response) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String msg = "";
        for (ObjectError error : allErrors) {
            msg += "[" + error.getDefaultMessage() + "]";
        }
        allErrors.get(0).getDefaultMessage();
        DataResult result = ResultUtils.FALL_ON_PARAMS.result();
        result.setMessage(msg);
        LOGGER.info("非法参数 : {}", e.getMessage());
        return result;
    }

    @ExceptionHandler(RuntimeException.class)
    public DataResult handleRuntimeException(RuntimeException e, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.error("", e);
        DataResult result = ResultUtils.FAIL_ON_ERROR.result();
        return result;
    }

    @ExceptionHandler(BusinessException.class)
    public DataResult handleBusinessException(BusinessException e, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.error("", e);
        DataResult result;
        if (Objects.nonNull(e.result())) {
            result = e.result();
            result.setMessage(e.getMessage());
        } else {
            result = ResultUtils.FAIL.message(e.getMessage());
        }

        return result;
    }

}
